import React, { PureComponent } from "react";
import { Card, Button, Spin, Form, Checkbox, Input } from "antd";
import { connect } from "dva";
import { withRouter } from "dva/router";
import styles from "./index.less";
import UsersTags from "../../../../components/usersTags/UsersTags";
import TransactorSelect from "../../../../components/flowdetailpannel/TransactorSelect";

import {
  getComponent,
  getFormProps,
} from "../../../flowmanage/formbuilder/FormItemDeal";
import { openNotificationWithIcon } from "../../../../utils/comm";

const { TextArea } = Input;
const defaultFields = [
  {
    code: "approval",
    defaultValue: "pass",
    name: "审批结果",
    options: [
      {
        key: "pass",
        name: "通过",
        id: "pass",
      },
      {
        key: "unpass",
        name: "不通过",
        id: "unpass",
      },
    ],
    readOnly: false,
    id: "approval",
    placeholder: "请选择",
    type: "dropdown",
    params: {},
    fieldType: "OptionFormField",
    required: true,
  },
  {
    code: "comment",
    defaultValue: "",
    name: "审批意见",
    readOnly: false,
    id: "comment",
    placeholder: "请输入",
    type: "multi-line-text",
    params: {},
    fieldType: "FormField",
    required: true,
  },
];

const formItemLayout = {
  labelCol: { span: 7 },
  wrapperCol: { span: 15 },
};
const formItemLayout1 = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14 },
};
const formItemLayout2 = {
  labelCol: { span: 2 },
  wrapperCol: { span: 10 },
};

@Form.create()
@withRouter
@connect(({ FlowHandle, loading, Public }) => ({
  flowHandleStore: FlowHandle,
  loading,
  Public,
}))
class FlowDeal extends PureComponent {
  constructor(props) {
    super(props);
    this.getComponent = getComponent.bind(this);
    this.getFormProps = getFormProps.bind(this);
    this.openNotificationWithIcon = openNotificationWithIcon.bind(this);
    this.state = {
      checked: false,
      usersVisible: false,
      usersSelectValue: [],
    };
  }

  componentDidMount() {
    const {
      location: {
        query: { formKey = "", processDefinitionId = "", taskId },
      },
      loading,
    } = this.props;
    const publicLoading = loading.models.Public;
    this.formKey = formKey;
    if (!taskId) return;
    this.processDefinitionId = processDefinitionId;
    this.taskId = taskId;
    if (publicLoading) {
      // 页面权限
      return;
    }
    this.getTaskForm();
  }

  componentDidUpdate(preProps) {
    const { loading } = this.props;
    const { loading: preLoading } = preProps;
    const publicLoading = loading.effects["Public/getResourceListByUserCode"];
    const prePubLoading =
      preLoading.effects["Public/getResourceListByUserCode"];
    if (prePubLoading === true && publicLoading === false) {
      this.getTaskForm();
    }
  }

  componentWillUnmount() {
    const { dispatch } = this.props;
    dispatch({ type: "FlowHandle/clearData" });
  }

  // 获取自定义表单
  getTaskForm = () => {
    const { taskId, formKey, processDefinitionId } = this;
    const { dispatch } = this.props;
    if (!formKey) {
      // 没有设置动态表单的，默认设置
      dispatch({ type: "FlowHandle/get/taskform", payload: defaultFields });
      return;
    }
    dispatch({
      type: "FlowHandle/getTaskform",
      payload: { taskId, formKey, processDefinitionId },
    }).then(({ errCode, errMsg }) => {
      if (errCode !== 0) {
        this.openNotificationWithIcon(
          "error",
          "",
          errMsg || "获取处理表单信息失败",
        );
      }
    });
  };

  handleFormDeal = (e) => {
    if (e && e.preventDefault) e.preventDefault();
    const { form, dispatch, flowHandleStore } = this.props;
    const { taskformFields = [] } = flowHandleStore;
    if (!this.taskId) return;
    form.validateFields((err, values) => {
      if (err) {
        return;
      }
      taskformFields.forEach((ele) => {
        const { code, id, type } = ele;
        const key = code || id;
        if (type === "date") {
          // 日期格式化
          const newValue = values[key];
          if (newValue) {
            values[key] = newValue.format("YYYY-MM-DD");
          }
        }
        if (type === "upload") {
          const newValue = (values[key] || [])
            .filter((f) => {
              if (f.status !== "done") {
                return false;
              }
              const { response: { datas = "" } = {} } = f;
              return datas.length > 0;
            })
            .map((f) => ({ [f.name]: f.response.datas }));
          values[key] = newValue;
        }
      });
      const { checked, usersSelectValue } = this.state;
      const { own_noticeDescription: noticeDescription } = values;
      const releaseNotice = { noticeDescription, receivers: usersSelectValue };
      const params = { variables: values, taskId: this.taskId };
      if (checked) {
        params.releaseNotice = releaseNotice;
        delete values.own_noticeDescription;
        delete values.own_receivers;
      }
      params.variables = values;
      dispatch({ type: "FlowHandle/handleTask", payload: params }).then(
        (data) => {
          const { errCode, errMsg } = data;
          if (errCode === 0) {
            if (checked) {
              dispatch({
                type: "PageNotice/getNoticeList",
                payload: { pageNum: 1, pageSize: 10, status: 0 },
              });
            }
            this.handleExit();
            return;
          }
          this.openNotificationWithIcon("error", "", errMsg || "处理失败");
        },
      );
    });
  };

  handleExit = () => {
    const { history } = this.props;
    // history.push('/flowimplement/flowhandle');
    history.goBack();
  };

  handleCheckChange = (e) => {
    const { checked } = e.target || {};
    this.setState({ checked });
  };

  handleUsersVisible = (visible = false) => {
    if (this.disable) return false;
    this.setState({ usersVisible: visible });
  };

  handleUsersSelect = (selectData) => {
    const { form } = this.props;
    form.setFieldsValue({ own_receivers: selectData });
    this.setState({ usersSelectValue: selectData, usersVisible: false });
  };

  handleDeleteUser = (e, item, userLists) => {
    e.preventDefault();
    e.stopPropagation();
    if (this.disable) return false;
    const newUsers = userLists.filter((nt) => nt.code !== item.code);
    this.handleUsersSelect(newUsers);
  };

  render() {
    const { loading, flowHandleStore, form, dispatch } = this.props;
    const disabled = this.disable;
    // window.form = form;
    const { checked, usersVisible, usersSelectValue } = this.state;
    const { formName, taskformFields = [] } = flowHandleStore;
    const { getFieldDecorator } = form;
    const dataLoading = loading.effects["FlowHandle/getTaskform"] || false;
    const handleTaskLoading = loading.effects["FlowHandle/handleTask"] || false;
    // const tasksLoding = loading.effects['FlowHandle/getCurrentTasks'];
    return (
      <div className={styles.root}>
        <Form>
          <Spin spinning={dataLoading} delay={300}>
            <div style={{ minHeight: window.innerHeight - 64 - 20 - 20 - 60 }}>
              <Card
                title={formName}
                bordered={false}
                className={styles.form_content}
              >
                {taskformFields.length > 0 ? (
                  <div className={styles.items_con}>
                    {taskformFields.map((ele) => {
                      const { options = [], name, code, id } = ele;
                      const {
                        itemProps = {},
                        formProps = {},
                      } = this.getFormProps(ele);
                      let expClassName = "";
                      let newFormItemLayout = formItemLayout;
                      // if (type === 'multi-line-text' || taskformFields.length < 3) {
                      //   expClassName = `${styles.item_col1}`;
                      // }
                      if (taskformFields.length < 3) {
                        expClassName = `${styles.item_col1}`;
                        newFormItemLayout = formItemLayout1;
                      }

                      if (!code && !id) {
                        return null;
                      }
                      return (
                        <div
                          key={id}
                          className={`${styles.items_col} ${expClassName}`}
                        >
                          <Form.Item label={name} {...newFormItemLayout}>
                            {getFieldDecorator(code || id, {
                              ...formProps,
                            })(
                              this.getComponent(
                                ele,
                                { ...itemProps, disabled },
                                options,
                                this.uploadProps,
                              ),
                            )}
                          </Form.Item>
                        </div>
                      );
                    })}
                  </div>
                ) : (
                  <span className={styles.nodata}>暂无表单数据</span>
                )}
              </Card>
              <div className={styles.check_content}>
                <div className={styles.check_title}>
                  <Checkbox checked={checked} onChange={this.handleCheckChange}>
                    处理后下发
                  </Checkbox>
                </div>
                {checked && (
                  <div className={styles.check_con}>
                    <Form.Item label="接收人" {...formItemLayout2}>
                      {getFieldDecorator("own_receivers", {
                        rules: [
                          { required: true, message: "请选择下发接收人" },
                        ],
                      })(
                        <div
                          className={`${styles.user__select} ${
                            disabled ? styles.user__select_disable : ""
                          }`}
                          onClick={() => {
                            this.handleUsersVisible(true);
                          }}
                        >
                          <Input style={{ display: "none" }} />
                          {usersSelectValue.length > 0 ? (
                            usersSelectValue.map((item) => (
                              <UsersTags
                                key={item.code}
                                label={item.name}
                                disabled={disabled}
                                onClick={(e) =>
                                  this.handleDeleteUser(
                                    e,
                                    item,
                                    usersSelectValue,
                                  )
                                }
                              />
                            ))
                          ) : (
                            <div className={styles.placeholder}>
                              请选择下发接收人
                            </div>
                          )}
                        </div>,
                      )}
                    </Form.Item>
                    <Form.Item label="下发说明" {...formItemLayout2}>
                      {getFieldDecorator("own_noticeDescription", {
                        initialValue: "",
                        rules: [
                          { max: 100, message: "请不要输入超过100个字符" },
                        ],
                      })(
                        <TextArea
                          disabled={disabled}
                          placeholder="请输入下发说明"
                          rows={4}
                        />,
                      )}
                    </Form.Item>
                  </div>
                )}
              </div>
            </div>
            <div className={styles.btns}>
              <Button
                loading={handleTaskLoading}
                type="primary"
                onClick={this.handleFormDeal}
              >
                提交
              </Button>
              <Button onClick={this.handleExit}>取消</Button>
            </div>
          </Spin>
        </Form>
        <TransactorSelect
          dispatch={dispatch}
          visible={usersVisible}
          selectData={usersSelectValue}
          onCancel={() => this.handleUsersVisible(false)}
          userSelect={this.handleUsersSelect}
          wrapClassName={styles.user_modal}
          title="接收人"
        />
      </div>
    );
  }
}

export default FlowDeal;
